/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

import { formatTime } from '@ohos/hvigor';
import { ArkUIXSdkInfoHandler, Component, PathAndApiVersion, SdkInfoConfig, SdkInfoHandler, ApiVersion } from '@ohos/sdkmanager-common';

import { ProjectBuildProfile } from '../../options/build/project-build-profile.js';
import { SdkArkUIXComponent } from '../impl/sdk-arkuix-component.js';
import { DefaultProgress } from '../lib/default-progress.js';
import { handleSdkException, proxyFun } from '../sdk-util.js';

import { CommonSdkInfo } from './common-sdk-info.js';
import ApiMeta = ProjectBuildProfile.ApiMeta;
import {VersionConst} from "../../const/version-const";

export class ArkUIXSdkInfo extends CommonSdkInfo {
  private readonly arkUIXSdkInfoHandler: SdkInfoHandler;
  private readonly arkUIXComponents: string[];
  private readonly projectArkUIXSdkPath: string;
  private sdkArkUIXComponent?: SdkArkUIXComponent;
  protected localLibComponents: Map<PathAndApiVersion, Component> = new Map<PathAndApiVersion, Component>();

  constructor(requireComponents: string[], sdkVersion: ApiMeta, sdkDir: string) {
    super(sdkVersion, sdkDir);
    this.arkUIXComponents = requireComponents;
    this.projectArkUIXSdkPath = sdkDir;

    // 初始化sdkHandler
    const sdkConfig: SdkInfoConfig = SdkInfoConfig.create(sdkDir).setSdkProxy(proxyFun);
    this.arkUIXSdkInfoHandler = new ArkUIXSdkInfoHandler(sdkConfig, new DefaultProgress());
  }

  async setup() {
    const start: [number, number] = process.hrtime();

    // 初始化需要的所有组件key
    const pathAndApis: PathAndApiVersion[] = [];
    const fullSdkVersion: ApiVersion = new ApiVersion(this.sdkVersion.fullVersion);
    this.arkUIXComponents.forEach((type) => pathAndApis.push(new PathAndApiVersion(type, fullSdkVersion)));
    try {
      this.localLibComponents = await this.arkUIXSdkInfoHandler.getOrDownload(pathAndApis);
    } catch (e) {
      handleSdkException(e);
    }
    pathAndApis.forEach((pathAndApi) => this.initComponent(this.contains(pathAndApi, this.localLibComponents)!));
    const time: [number, number] = process.hrtime(start);
    this._log.debug(`Sdk init in ${formatTime(time)}`);
  }

  contains(pathAndApi: PathAndApiVersion, all: Map<PathAndApiVersion, Component>) {
    for (const [key, component] of all) {
      if (key.equals(pathAndApi)) {
        return component;
      }
    }
    return undefined;
  }

  protected initComponent(component: Component) {
    this.sdkArkUIXComponent = new SdkArkUIXComponent(component);
  }

  getArkUIXRootPath(): string {
    return this.sdkArkUIXComponent!.getBaseDir();
  }

  /**
   * 在ArkUI-x插件中使用,不能删除
   * @returns {string} 获取工程的ArkUI sdk的路径
   */
  getProjectArkUIXSdkPath(): string {
    return this.projectArkUIXSdkPath;
  }
}
